package com.jrx.anytxn.param.transaction.job.billCompare.step;

import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlBillTransCompareDetail;
import com.jrx.anytxn.param.entity.TlThirdBillDetail;
import com.jrx.anytxn.param.mapper.ext.ExtTlThirdBillDetailMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.transaction.config.BillCompareConfig;
import com.jrx.anytxn.param.transaction.job.billCompare.bean.ThirdBillDetilReadBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
import com.jrx.anytxn.transaction.entity.TlDisbursementLog;
import com.jrx.anytxn.transaction.entity.TlGlInterfaceInfo;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlDisbursementLogMapper;
import com.jrx.anytxn.transaction.mapper.ext.ExtTlGlInterfaceInfoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
public class BillDetailForXFProcessor implements ItemProcessor<AmLoanMainInfo, ThirdBillDetilReadBean> {

    private static final Logger logger = LoggerFactory.getLogger(BillDetailForXFProcessor.class);

    @Resource
    private ExtTlThirdBillDetailMapper extTlBillThirdDetailMapper;
    @Autowired
    private ISegmentService iSegmentService;
    @Autowired
    private BillCompareConfig billCompareConfig;
    @Resource
    private ExtTlGlInterfaceInfoMapper extTlGlInterfaceInfoMapper;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ExtTlDisbursementLogMapper extTlDisbursementLogMapper;

    @Override
    public ThirdBillDetilReadBean process(AmLoanMainInfo item) throws Exception {

        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.XIB_ORG_NUMBER);
        // 设置指定对账日期
        Date today = billCompareConfig.getToday();
        if (Objects.nonNull(today)) {
            org.setToday(today);
        }
        today = org.getToday();
        boolean contains = Arrays.asList("PCP", "T24").contains(item.getThirdChannel());
        List<TlThirdBillDetail> tlBillTransDetailList = new ArrayList<>();
        List<TlBillTransCompareDetail> tlBillTransCompareDetailList = new ArrayList<>();
        ThirdBillDetilReadBean billDetailReadBean = new ThirdBillDetilReadBean();
        // 三方明细
        TlThirdBillDetail detail = extTlBillThirdDetailMapper.selectByThirdSeqAndType(item.getSerialNumber(), item.getTenantId(),
                billCompareConfig.getThirdChannel(), contains ? "I" : Constant.TRANSACTION_TYPE_XF);
        // PCP当天取消的只会提供一条记录
        if (contains && item.getPostingDate().compareTo(today) == 0) {
            TlDisbursementLog disLog = extTlDisbursementLogMapper.selectDisbursementByCondition(item.getLoanId(), item.getCustomerId(), item.getTenantId());
            if (Objects.nonNull(disLog)
                    && TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_F.equalsIgnoreCase(disLog.getSumStatus())
                    && TransBizConstant.CANCLE_STATUS_1.equalsIgnoreCase(disLog.getCancelStatus())
                    && disLog.getCollateDate().compareTo(today) == 0) {
                if (Objects.isNull(detail)) {
                    return null;
                }
                buildTlThirdBillDetail(tlBillTransDetailList, detail);
                billDetailReadBean.setTlBillTransDetilList(tlBillTransDetailList);
                return billDetailReadBean;
            }
        }
        // 营销费用
        List<TlGlInterfaceInfo> gls = extTlGlInterfaceInfoMapper.selectByTxnCodeAllGl(item.getLoanId(), item.getCustomerId(), "T54000", item.getTenantId());
        BigDecimal reduce = gls.stream().map(TlGlInterfaceInfo::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        // 单笔借据总金额
        BigDecimal loanAmount = item.getLoanAmount();
        BigDecimal totalLoanAmount = loanAmount.add(reduce);
        item.setLoanAmount(totalLoanAmount);
        String organizationId = item.getOrganizationId();


        // 是否当日的数据
        boolean todayLoan = today.compareTo(item.getPostingDate()) == 0;
        // 1.是当日的数据
        if (todayLoan) {
            // 构建一个虚假的交易对象
            if (Objects.isNull(detail) || Objects.isNull(detail.getId())) {
                detail = new TlThirdBillDetail();
                detail.setTransStatus("6");
                detail.setBusinessDate(today);
                detail.setTransactionAmount(BigDecimal.ZERO);
            }
            String transStatus = detail.getTransStatus();
            Date businessDate = detail.getBusinessDate();
            if (contains && Objects.nonNull(detail.getId())) {
                detail.setTransactionAmount(totalLoanAmount);
            }
            BigDecimal transactionAmount = detail.getTransactionAmount();
            boolean transCompareStatus = (!"000000000".equals(transStatus) && !"0".equals(transStatus));
            if (Objects.nonNull(detail.getId())) {
                if (transCompareStatus || totalLoanAmount.compareTo(transactionAmount) != 0) {
                    buildTlBillTransCompareDetail(item, tlBillTransCompareDetailList, totalLoanAmount, organizationId, transStatus, businessDate, transactionAmount);
                }
                buildTlThirdBillDetail(tlBillTransDetailList, detail);
            } else {
                buildTlBillTransCompareDetail(item, tlBillTransCompareDetailList, totalLoanAmount, organizationId, transStatus, businessDate, transactionAmount);
            }
        } else if (Objects.nonNull(detail)) {
            // 2.非当日的数据且三方明细不为空
            String transStatus = detail.getTransStatus();
            Date businessDate = detail.getBusinessDate();
            if (contains && Objects.nonNull(detail.getId())) {
                detail.setTransactionAmount(totalLoanAmount);
            }
            BigDecimal transactionAmount = detail.getTransactionAmount();
            boolean transCompareStatus = (!"000000000".equals(transStatus) && !"0".equals(transStatus));
            if (transCompareStatus || loanAmount.compareTo(transactionAmount) != 0) {
                buildTlBillTransCompareDetail(item, tlBillTransCompareDetailList, totalLoanAmount, organizationId, transStatus, businessDate, transactionAmount);
            }
            buildTlThirdBillDetail(tlBillTransDetailList, detail);
        } else {
            logger.warn("该用户{}的交易借据{}非当日{}，且没有三方明细", item.getCustomerId(), item.getLoanId(), today);
        }

        billDetailReadBean.setTlBillTransDetilList(tlBillTransDetailList);
        billDetailReadBean.setTlBillTransCompareDetailList(tlBillTransCompareDetailList);
        return billDetailReadBean;
    }

    /**
     * 设置对账明细
     * @param tlBillTransDetailList
     * @param detail
     */
    public void buildTlThirdBillDetail(List<TlThirdBillDetail> tlBillTransDetailList, TlThirdBillDetail detail) {
        TlThirdBillDetail updata = new TlThirdBillDetail();
        updata.setId(detail.getId());
        updata.setCompareFlag(Constant.COMPARE_FLAG_1);
        updata.setDataFrom(billCompareConfig.getDataFrom());
        tlBillTransDetailList.add(updata);
    }

    /**
     * 构建对账结果明细表对象
     * @param item
     * @param tlBillTransCompareDetailList
     * @param loanAmount
     * @param organizationId
     * @param transStatus
     * @param businessDate
     * @param transactionAmount
     * @throws SegmentException
     */
    public void buildTlBillTransCompareDetail(AmLoanMainInfo item, List<TlBillTransCompareDetail> tlBillTransCompareDetailList, BigDecimal loanAmount, String organizationId, String transStatus, Date businessDate,
                                              BigDecimal transactionAmount) throws SegmentException {
        TlBillTransCompareDetail tlBillTransCompareDetail = new TlBillTransCompareDetail();
        tlBillTransCompareDetail.setId(iSegmentService.getId("TlBillTransCompareDetail"));
        tlBillTransCompareDetail.setTenantId(item.getTenantId());
        tlBillTransCompareDetail.setOrganizationId(organizationId);
        tlBillTransCompareDetail.setBillType(Constant.TRANSACTION_TYPE_XF);
        tlBillTransCompareDetail.setCompareStatus(Constant.COMPARE_FLAG_0);
        tlBillTransCompareDetail.setCompareDesc("消费金额或状态不平");
        tlBillTransCompareDetail.setCustomerId(item.getCustomerId());
        tlBillTransCompareDetail.setLoanNumber(item.getLoanId());
        tlBillTransCompareDetail.setSeqNo(item.getSerialNumber());
        tlBillTransCompareDetail.setDetailAmount(transactionAmount);
        tlBillTransCompareDetail.setTxnPostingAmnt(loanAmount);
        tlBillTransCompareDetail.setBillTransStatus(transStatus);
        tlBillTransCompareDetail.setTxnTransStatus(TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S);
        tlBillTransCompareDetail.setDataFrom(billCompareConfig.getDataFrom());
        tlBillTransCompareDetail.setBusinessDate(businessDate);
        tlBillTransCompareDetail.setThirdChannel(item.getThirdChannel());
        tlBillTransCompareDetailList.add(tlBillTransCompareDetail);
    }

}
